package foo.bar.wiki.security;

import org.apache.shiro.mgt.*;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.subject.support.DelegatingSubject;
import org.apache.shiro.web.mgt.DefaultWebSubjectFactory;
import org.apache.shiro.web.subject.support.WebDelegatingSubject;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * @author tmjee
 * @version $Date$ $Id$
 */
public class AnonymousSubjectAwareDefaultSubjectFactory extends DefaultWebSubjectFactory {

    protected Subject newSubjectInstance(PrincipalCollection principals, boolean authenticated,
                                         String host, Session session,
                                         ServletRequest request, ServletResponse response,
                                         SecurityManager securityManager) {
        //return new WebDelegatingSubject(principals, authenticated, host, session, request, response, securityManager);
        // when the principals is null or empty, that means the login was not successfull,
        // here we give it the anonymous account's principals.
        if(principals == null || principals.isEmpty()) {
            if (null == UserAccountRealm.ANONYMOUS_USER_ACCOUNT) {
                throw new RuntimeException("UserAccountRealm.ANONYMOUS_USER_ACCOUNT is null, this should be setup in SetupService, check if SetupService has been configured and started up properly");
            }
            return new AnonymousSubjectAwareDelegatingSubject(
                            UserAccountRealm.ANONYMOUS_USER_ACCOUNT.getPrincipals(),
                            authenticated, host, session, request, response, securityManager);
        }
        return new AnonymousSubjectAwareDelegatingSubject(principals, authenticated, host,
                session, request, response, securityManager);
    }


}
